package com.dpiinc.TechPage.video;

import android.content.Context;
import android.util.Log;

import com.dpiinc.TechPage.AIWriteApplication;
import com.coremedia.iso.boxes.Container;
import com.googlecode.mp4parser.authoring.Movie;
import com.googlecode.mp4parser.authoring.Track;
import com.googlecode.mp4parser.authoring.builder.DefaultMp4Builder;
import com.googlecode.mp4parser.authoring.container.mp4.MovieCreator;
import com.googlecode.mp4parser.authoring.tracks.AppendTrack;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

public class JoinVideo {

    private Context context;
    //需要拼接的mp4视频的地址
    private List<String> videoUris;
    //合并完毕，导出地址
    private String output;
    //是否正在执行合并任务
    public boolean isRunning = false;
    private List<String> allJoin = new ArrayList<>();
    private int index=0;

    public JoinVideo(Context context, List<String> videoUris) {
        this.context = context;
        this.videoUris = videoUris;
    }

    public boolean isRunning() {
        return isRunning;
    }

    public void joinVideo() {
        isRunning = true;

        if (videoUris == null || videoUris.size() <= 0) {
            throw new IllegalArgumentException();
        }

        if (videoUris.size() == 1) { // 只有一个视频片段，不需要合并
            StrokeToBitmap.getInstance().getfinalpath(videoUris.get(0));
        } else if (videoUris.size() == 2) {
            if (startJoin(videoUris)){
                StrokeToBitmap.getInstance().getfinalpath(output);
            }else {
                StrokeToBitmap.getInstance().getfinalpath(null);
            }
        } else {
            for (int i = 0; i < videoUris.size(); i++) {
                List<String> firsttemp = new ArrayList<>();
                firsttemp.add(videoUris.get(i));
                firsttemp.add(videoUris.get(i + 1));
                videoUris.remove(i + 1);
                videoUris.remove(i);
                i--;
                if (startJoin(firsttemp)) {
                    allJoin.add(output);
                } else {
                    break;
                }
            }
            for (int i = 0; i < 1000; i++) {
                List<String> temp = new ArrayList<>();
                if (allJoin.size() > 1) {
                    temp.add(allJoin.get(0));
                    temp.add(allJoin.get(1));
                    allJoin.remove(1);
                    allJoin.remove(0);
                    if (startJoin(temp)) {
                        allJoin.add(0, output);
                    } else {
                        break;
                    }
                } else {
                    StrokeToBitmap.getInstance().getfinalpath(output);
                    break;
                }
            }
        }
//        startJoin(videoUris);
    }

    private Boolean startJoin(List<String> Uris) {
        index++;
        try {
            SimpleDateFormat df = new SimpleDateFormat("MM-dd-HH:mm:ss");//设置日期格式
            System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
            output = AIWriteApplication.instance.getDatabasePath("aiwirte") + "/aiwirtetemp/" + df.format(new Date())+index + ".mp4";

            List<Movie> inMovies = new ArrayList<>();

            for (String videoUri : Uris) {
                File f = new File(videoUri);
                //文件存在
                if (f.exists()) {
                    inMovies.add(MovieCreator.build(videoUri));
                }
            }

            // 分别取出音轨和视频
            List<Track> videoTracks = new LinkedList<>();
            List<Track> audioTracks = new LinkedList<>();
            for (Movie m : inMovies) {
                for (Track t : m.getTracks()) {
                    if (t.getHandler().equals("soun")) {
                        audioTracks.add(t);
                    }
                    if (t.getHandler().equals("vide")) {
                        videoTracks.add(t);
                    }
                }
            }

            // 合并到最终的视频文件
            Movie outMovie = new Movie();

            if (!audioTracks.isEmpty()) {
                outMovie.addTrack(new AppendTrack(audioTracks.toArray(new Track[audioTracks.size()])));
            }
            if (!videoTracks.isEmpty()) {
                outMovie.addTrack(new AppendTrack(videoTracks.toArray(new Track[videoTracks.size()])));
            }

            Container mp4file = new DefaultMp4Builder().build(outMovie);

            // 将文件输出
            File resultFile = new File(output);

            //删除resultFile
            if (resultFile.exists() && resultFile.isFile()) {
                resultFile.delete();
            }

            FileChannel fc = new RandomAccessFile(resultFile, "rw").getChannel();
            if (fc!=null) {
                mp4file.writeContainer(fc);
                fc.close();
            }
//             合成完成后把原片段文件删除
            for (String filePath : Uris) {
                File file = new File(filePath);
                file.delete();
            }

            isRunning = false;
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.i("JoinVideo", "--文件找不到异常--");

            isRunning = false;
            return false;
        } catch (Exception e) {
            e.printStackTrace();

            isRunning = false;
            Log.i("JoinVideo", "--拼接失败--" + e);
            return false;
        }
    }
}
